package com.hw.backapi.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.hw.backapi.service.INappyBrandService;
import com.hw.model.entity.NappyBrandPO;
import com.hw.model.mapper.NappyBrandMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.model.vo.nappy.ThreeLevelDataVO;
import com.hw.model.vo.nappy.ThreeLevelInfoVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者
 * @since 2022-11-28
 */
@Service
public class NappyBrandServiceImpl extends ServiceImpl<NappyBrandMapper, NappyBrandPO> implements INappyBrandService {

    @Override
    public List<ThreeLevelInfoVO> getThreeLevelData() {
        List<ThreeLevelDataVO> threeLevelData = this.baseMapper.getThreeLevelData();
        if(CollectionUtil.isEmpty(threeLevelData)){
            return Collections.EMPTY_LIST;
        }

        Map<Long, Map<Long, List<ThreeLevelDataVO>>> dataMap = threeLevelData.parallelStream().collect(Collectors.groupingBy(ThreeLevelDataVO::getTypeId, Collectors.groupingBy(ThreeLevelDataVO::getCategoryId)));

        List<ThreeLevelInfoVO> threeLevelInfoVOS = new ArrayList<>();
        dataMap.entrySet().forEach(entry->{
            ThreeLevelInfoVO one = new ThreeLevelInfoVO();

            List<ThreeLevelInfoVO> twoList = entry.getValue().entrySet().stream().map(threeLevelDataVOENTRY -> {
                ThreeLevelInfoVO two = new ThreeLevelInfoVO();
                List<ThreeLevelInfoVO> threeList = threeLevelDataVOENTRY.getValue().parallelStream().map(threeLevelDataVO -> {
                    ThreeLevelInfoVO three = new ThreeLevelInfoVO();
                    three.setValue(threeLevelDataVO.getName());
                    three.setLabel(threeLevelDataVO.getName());
                    return three;
                }).collect(Collectors.toList());

                one.setValue(threeLevelDataVOENTRY.getValue().get(0).getTypeName());
                one.setLabel(threeLevelDataVOENTRY.getValue().get(0).getTypeName());

                two.setLabel(threeLevelDataVOENTRY.getValue().get(0).getCateName());
                two.setValue(threeLevelDataVOENTRY.getValue().get(0).getCateName());
                two.setChildren(threeList);
                return two;
            }).collect(Collectors.toList());


            one.setChildren(twoList);

            threeLevelInfoVOS.add(one);
        });
        return threeLevelInfoVOS;
    }
}
